<template>
    <div>
        <Headline :headline1="$t('m.SystemManagement')+'  /  '" :headline2="$t('m.CustomerUserManagement')"/>
        <a-card style="width: 100%">
            <a-select
                    default-value="-1"
                    style="width: 120px; margin-right: 20px"
                    @change="commChange"
            >
                <a-select-option :value="item.code" :key="item.code" v-for="item in dataTreeListA"> {{item.name}}
                </a-select-option>
            </a-select>
            <a-select
                    default-value="-1"
                    style="width: 150px; margin-right: 20px"
                    @change="schoolChange"
            >
                <a-select-option :value="item.code" :key="item.code" v-for="item in dataTreeList"> {{item.name}}
                </a-select-option>
            </a-select>
            <a-input-search
                    style="width: 200px; margin-right: 20px"
                    :placeholder="$t('m.PleaseEnterYourSearchTerms')"
                    enter-button
                    @search="onSearch"
                    v-model="forminitial.key"
            />
            <a-button type="primary" icon="plus"
                      v-if="isTrue('sys:cust:user:adduser')"
                      @click="addUser">{{$t('m.AddUser')}}
            </a-button>
            <a-table
                    size="small"
                    style="margin-top: 20px"
                    :columns="columns"
                    :rowKey="(record, i) => i"
                    :data-source="data"
                    :pagination="false"
                    :row-selection="{
          onChange: onSelectChange,
          type: 'radio',
        }"
                    bordered
            >
                <div slot="show" slot-scope="text, tags, i">
                    <a-button type="primary" @click="showTable(text, tags, i)"
                    >{{$t('m.Examine')}}
                    </a-button
                    >
                </div>
            </a-table>
            <a-pagination
                    style="margin-top: 10px"
                    show-size-changer
                    :default-current="1"
                    :total="total"
                    @change="Pages"
                    :pageSizeOptions="['5', '10', '30', '40']"
                    @showSizeChange="onShowSizeChange"
                    class="pages"
            />
        </a-card>

        <a-drawer
                width="1000px"
                :title="$t('m.SystemUser')"
                placement="right"
                :visible="tableVisible"
                @ok="tableHandleOk"
                @close="tableHandleCancel"
        >
            <a-button
                    type="primary"
                    icon="edit"
                    style="margin-right: 20px"
                    @click="editUserInfo"
                    v-if="isTrue('sys:cust:user:updateuser')"
            >{{$t('m.EditUser')}}
            </a-button
            >
            <a-button
                    type="danger"
                    @click="delUserInfo"
                    icon="delete"
                    style="margin-right: 20px"
                    v-if="isTrue('sys:cust:user:deluser')"
            >{{$t('m.DeleteUser')}}
            </a-button
            >
            <a-button type="primary" @click="reset"
                      v-if="isTrue('sys:cust:user:reset')"
                      icon="plus">{{$t('m.ResetPasswords')}}
            </a-button>
            <a-table
                    style="margin-top: 20px"
                    size="small"
                    :columns="columnsA"
                    :rowKey="(record, i) => i"
                    :data-source="dataA"
                    :pagination="false"
                    :row-selection="{
          onChange: onSelectChangeC,
          type: 'radio',
          selectedRowKeys: locosclete
        }"
                    bordered
            >
                <div slot="status" slot-scope="text, tags, i">
                    <a-switch
                            :disabled="!isTrue('sys:cust:user:valid')"
                            :checked="tags.status == 0 ? false : true"
                            @change="onSwitch(text, tags, i)"
                    />
                </div>
                <div slot="accredit" slot-scope="text, tags, i">
                    <a-button @click="accredit(text, tags, i)" type="primary"
                    >{{$t('m.Authorization')}}
                    </a-button
                    >
                </div>
            </a-table>
        </a-drawer>

        <a-modal
                :title="$t('m.SystemSystemAuthorization')"
                :visible="visibleD"
                @cancel="handleCancelD"
                :autoExpandParent="true"
                @ok="handleOkD"
                :cancelText="$t('m.Cancel')"
                :okText="$t('m.Ok')"
        >
            {{$t('m.SelectSystemRole')}}
            <a-select
                    style="width: 150px; margin-right: 20px"
                    @change="ChangeA"
            >
                <a-select-option :value="item.roleId" :key="item.roleId"
                                 v-for="(item) in datalistB"
                >
                    {{item.roleName}}
                </a-select-option>
            </a-select>
            <a-tree
                    auto-expand-parent
                    :tree-data="treeData"
                    :replaceFields="replaceFields"
            />
        </a-modal>
        <a-modal
                :title="$t('m.SystemUserInformation')"
                :visible="userVisible"
                @cancel="userHandleCancel"
                :footer="null"
        >
            <a-form
                    :form="form"
                    :label-col="{ span: 7 }"
                    :wrapper-col="{ span: 12 }"
                    @submit="handleSubmit"
            >
                <a-form-item :label="$t('m.UserType')">
                    <a-select
                            v-decorator="[
              'userType',{rules: [{ required: true, message: 'Please select your gender!' }]}]"
                            :placeholder="$t('m.pleaseChoose')"
                    >
                        <a-select-option v-if="this.custlevel == 0" value="0"> 开发者</a-select-option>
                        <a-select-option v-if="this.custlevel == 0" value="1"> 厂家</a-select-option>
                        <a-select-option v-if="this.custlevel == 0" value="2"> 代理商</a-select-option>
                        <a-select-option value="3"> 管理员</a-select-option>
                        <a-select-option value="4"> 普通管理员</a-select-option>
                    </a-select>
                </a-form-item>
                <a-form-item :label="$t('m.SystemAccount')">
                    <a-input
                            v-decorator="['userCode',{rules: [{ required: true, message: 'Please input your note!' }]}]"
                    />
                </a-form-item>
                <a-form-item :label="$t('m.LoginPassword')" v-if="this.handleUserType=='add'">
                    <a-input
                            v-decorator="['password',{rules: [{ required: true, message: 'Please input your note!' }]}]"
                    />
                </a-form-item>
                <a-form-item :label="$t('m.Nickname')">
                    <a-input
                            v-decorator="['nickname',{rules: [{ required: true, message: 'Please input your note!' }]}]"
                    />
                </a-form-item>
                <a-form-item :label="$t('m.IsEnabled')">
                    <a-radio-group name="status"
                                   v-decorator="['status']">
                        <a-radio :value="1"> {{$t('m.normal')}}</a-radio>
                        <a-radio :value="0"> {{$t('m.forbidden')}}</a-radio>
                    </a-radio-group>
                </a-form-item>
                <a-form-item :wrapper-col="{ span: 12, offset: 5 }">
                    <a-button type="primary" html-type="submit"> {{$t('m.Ok')}}</a-button>
                </a-form-item>
            </a-form>
        </a-modal>

        <a-modal
                :title="$t('m.NewPassword')"
                :visible="visibleB"
                :cancelText="$t('m.Cancel')"
                :okText="$t('m.Ok')"

                @ok="handleOkB"
                @cancel="handleCancelB"
        >
            {{$t('m.NewPassword')}}
            <a-input type="text" v-model="newPassword" style="width: 200px"/>
        </a-modal>
        <a-modal
                :title="$t('m.AuthorizedRole')"
                :visible="visibleC"
                @cancel="handleCancelC"
                :footer="null"
        >
            <a-button type="primary" @click="addOrgin"
                      v-if="isTrue('sys:cust:user:addrole')"
            >{{$t('m.TheNewAuthorization')}}
            </a-button>
            <a-table
                    size="small"
                    style="margin-top: 20px"
                    :columns="columnsC"
                    :rowKey="(record, i) => i"
                    :data-source="dataC"
                    :pagination="false"
                    bordered
            >
                <div slot="num" slot-scope="text,tags,i">
                    {{i + 1}}
                </div>
                <div slot="del" slot-scope="text,tags,i">
                    <a-button type="primary"
                              :disabled="!isTrue('sys:cust:user:delrole')"
                              @click="delRole(text,tags,i)">{{$t('m.DeleteTheAuthorized')}}
                    </a-button>
                </div>
            </a-table>
        </a-modal>
        <Delete ref="delcom" :dalete="dalete" @confirm="delOk"/>
        <Delete ref="delcomA" :dalete="daleteA" @confirm="delOkA"/>
        <Delete ref="delcomB" :dalete="daleteB" @confirm="delOkB"></Delete>
    </div>
</template>

<script>
    import Headline from "@/components/Headline";
    import Delete from "@/components/Delete"
    import {
        addRoleUser,
        delRoleUser,
        getCustomerList,
        getCustSysUserList,
        getRoleByUserId
    } from "@/api/systemmanagement";
    import {getStaff} from "@/api/perAges";
    import {Setperms} from '@/assets/js/setperms'
    import {getWidgetDictionaryList} from "@/api/entrance/cloudDoor";
    import {
        getDelSysUser,
        getonOffAccount,
        getResetPassword,
        getRoleList,
        getRoleMenuTreeByRoleId,
        getsaveSysUser
    } from "@/api/User";

    export default {
        name: "ClientAdministration",
        components: {Headline, Delete},
        data() {
            return {
                datas: "",
                forminitialG: {
                    groupcode: "SYS0000003",
                    insertall: "-1|全部",
                    where: "code<> -1 and code <> -100",
                },
                forminitialH: {
                    groupcode: "SYS0000002",
                    insertall: "-1|全部",
                    where: "code<> -1 and code <> -100",
                },
                dataTreeList: [],
                dataTreeListA: [],
                okDelkey: {},
                dalete: {
                    titles: this.$t('m.DeleteThePrompt'),
                    type: 'exclamation-point',
                    text: this.$t('m.AreYouSureToDeleteThisData')
                },
                daleteA: {
                    titles: this.$t('m.ChangeStatus'),
                    type: 'exclamation-point',
                    text: this.$t('m.AreYouSureToChangeuserStatus')
                },
                daleteB: {
                    titles: this.$t('m.ChangeStatus'),
                    type: 'exclamation-point',
                    text: this.$t('m.AreYouSureToChangeuserStatus')
                },
                visibleC: false,
                newPassword: "",
                visibleB: false,
                data: [],
                forminitial: {
                    start: 0,
                    limit: 10,
                    key: "",
                    page: 1,
                    custLevel: -1,
                    custType: -1,
                },
                locosclete: [],
                columns: [
                    {
                        title: this.$t('m.CustomerID'),
                        dataIndex: "custcode",
                    },
                    {
                        title: this.$t('m.CustomerLevel'),
                        dataIndex: "custlevelname",
                    },
                    {
                        title: this.$t('m.CustomerName'),
                        dataIndex: "custname",
                    },
                    {title: this.$t('m.Operation'), scopedSlots: {customRender: "show"}},
                ],
                radio: "radio",
                total: 0,
                selectedRowKeys: [],
                radioFlag: false,
                false: true,
                tableVisible: false,
                dataA: [],
                columnsA: [
                    {
                        title: this.$t('m.SystemAccount'),
                        dataIndex: "userCode",
                    },
                    {
                        title: this.$t('m.Name'),
                        dataIndex: "nickname",
                    },
                    {
                        title: this.$t('m.UserType'),
                        dataIndex: "userType",
                        customRender: function (text) {
                            if (text == '0') {
                                return '开发者'
                            }
                            if (text == '1') {
                                return '厂家'
                            }
                            if (text == '2') {
                                return '代理商'
                            }
                            if (text == '3') {
                                return '管理员'
                            }
                            if (text == '4') {
                                return '普通操作员'
                            }
                        }
                    },
                    {
                        title: this.$t('m.LoginNumber'),
                        dataIndex: "logintime",
                    },
                    {
                        title: this.$t('m.LastLogin'),
                        dataIndex: "lastlogindate",
                    },
                    {
                        title: this.$t('m.LastLoginIP'),
                        dataIndex: "lastloginip",
                    },
                    {
                        title: this.$t('m.Status'),
                        dataIndex: "status",
                        scopedSlots: {customRender: "status"},
                    },
                    {
                        title: this.$t('m.RegistrationDate'),
                        dataIndex: "createDate",
                    },
                    {
                        title: this.$t('m.Operation'),
                        scopedSlots: {customRender: "accredit"},
                    },
                ],
                forminitialA: {
                    start: 0,
                    limit: 10,
                    page: 1,
                    custId: "",
                },
                demoUserId: 0,
                flag: true,
                form: this.$form.createForm(this, {name: "coordinated"}),
                userVisible: false,
                dataList: {},
                demoList: [],
                dataC: [],
                columnsC: [
                    {
                        title: this.$t('m.Equipmentserialnumber'),
                        scopedSlots: {customRender: "num"},
                    },
                    {
                        title: this.$t('m.CharacterName'),
                        dataIndex: "roleName",
                    },
                    {
                        title: this.$t('m.Operation'),
                        scopedSlots: {customRender: "del"},
                    },
                ],
                visibleD: false,
                forminitialC: {
                    limit: 1000,
                    start: 0,
                    page: 1
                },
                datalistB: [],
                treeData: [],
                replaceFields: {
                    children: 'children', title: 'menuName', key: 'menuId'
                },
                addRole: {
                    userId: '',
                    roleId: ''
                },
                roleIdDel: '',
                // 用户操作类型：新增/修改
                handleUserType: 'add',
                custlevel: ''
            };
        },
        created() {
            this.getClientList();
            this.parms = Setperms(this.$route.fullPath, JSON.parse(sessionStorage.getItem('menu')))
            this.custlevel = JSON.parse(localStorage.getItem("userinfo")).custlevel;
            console.log(this.custlevel);
            getWidgetDictionaryList({params: this.forminitialG})
                .then((res) => {
                    this.dataTreeList = res.data.data;
                    console.log(res);
                })
                .catch((err) => {
                    console.log(err);
                });
            getWidgetDictionaryList({params: this.forminitialH})
                .then((res) => {
                    this.dataTreeListA = res.data.data;
                    console.log(res);
                })
                .catch((err) => {
                    console.log(err);
                });
        },
        methods: {
            isTrue(str) {
                return this.parms.indexOf(str) !== -1;
            },
            delOk() {
                delRoleUser({userId: this.addRole.userId, roleId: this.roleIdDel})
                    .then(res => {
                        if (res.data.success == true) {
                            this.getRoleByUserList()
                            this.$message.success("删除授权成功");
                        }
                        if (res.data.success == false) {
                            this.$message.error(res.data.msg);
                        }
                    })
                    .catch(err => {
                        this.$message.error("操作失败");
                    })
                this.$refs.delcom.visible = false
            },
            delRole(text, tags, i) {
                this.roleIdDel = tags.roleId
                this.$refs.delcom.visible = true

            },
            handleOkD() {
                let params = JSON.parse(JSON.stringify(this.addRole))
                if (params.roleId == '') return this.$message.warning('请选择角色')
                addRoleUser(params)
                    .then(res => {
                        if (res.data.success == true) {
                            this.getRoleByUserList()
                            this.$message.success("授权成功");
                        }
                        if (res.data.success == false) {
                            this.$message.error(res.data.msg);
                        }
                        console.log(res)
                    })
                    .catch(err => {
                        this.$message.error("操作失败");
                    })
                this.visibleD = false

            },
            ChangeA(value) {
                console.log(value)
                this.addRole.roleId = value
                getRoleMenuTreeByRoleId({params: {roleId: value}})
                    .then(res => {
                        this.treeData = res.data
                    })
                    .catch(err => {
                        console.log(err)
                    })
            },
            addOrgin() {
                // this.visibleC = false
                this.visibleD = true
                getRoleList({params: this.forminitialC})
                    .then(res => {
                        this.datalistB = res.data.data
                        console.log(res)
                    })
                    .catch(err => {
                        console.log(err)
                    })
            },
            handleCancelC() {
                this.visibleC = false;
            },

            handleCancelD() {
                this.visibleD = false
            },
            accredit(text, tags, i) {
                this.addRole.userId = tags.userId
                this.visibleC = true;
                this.getRoleByUserList()
            },
            getRoleByUserList() {
                getRoleByUserId({params: {userId: this.addRole.userId}})
                    .then(res => {
                        this.dataC = res.data.data
                        console.log(res.data)
                    })
                    .catch(err => {
                        console.log(err)
                    })
            },
            handleCancelB() {
                this.visibleB = false;
                this.newPassword = "";
            },
            handleOkB() {
                getResetPassword({
                    userId: this.dataList.userId,
                    password: this.newPassword,
                })
                    .then((res) => {
                        if (res.data.success == true) {
                            this.$message.success("密码修改成功");
                        }
                        if (res.data.success == false) {
                            this.$message.error("密码修改失败");
                        }
                    })
                    .catch((err) => {
                        this.$message.error("操作失败");
                    });
                this.visibleB = false;
                this.newPassword = "";
            },
            // Object.getOwnPropertyNames
            reset() {
                if (
                    Object.getOwnPropertyNames(JSON.parse(JSON.stringify(this.dataList)))
                        .length == 0
                )
                    return this.$message.warning("请选择系统用户");
                this.visibleB = true;
            },
            delOkB() {

                getDelSysUser({userId: this.dataList.userId})
                    .then((res) => {
                        if (res.data.success == true) {
                            this.$message.success("删除成功");
                            this.getDataListA();
                        }
                        if (res.data.success == false) {
                            this.$message.error("删除失败");
                        }
                    })
                    .catch((err) => {
                        this.$message.error("操作失败");
                    });
                this.$refs.delcomB.visible = false
            },
            delUserInfo() {

                if (
                    Object.getOwnPropertyNames(JSON.parse(JSON.stringify(this.dataList)))
                        .length == 0
                )
                    return this.$message.warning("请选择系统用户");
                this.$refs.delcomB.visible = true

            },
            editUserInfo() {
                this.flag = false;
                this.handleUserType = 'edit';
                if (this.demoList.length <= 0) return this.$message.warning('请选择系统用户')
                this.userVisible = true;
                this.demoUserId = this.dataList.userId
                this.forminitialA.custId = this.dataList.custId
                setTimeout(() => {
                    if (this.dataList.userType == '3') {
                        this.form.setFieldsValue({
                            userType: '管理员',
                            userCode: this.dataList.userCode,
                            nickname: this.dataList.nickname,
                            status: this.dataList.status
                        });
                    }
                    if (this.dataList.userType == '4') {
                        this.form.setFieldsValue({
                            userType: '普通操作员',
                            userCode: this.dataList.userCode,
                            nickname: this.dataList.nickname,
                            status: this.dataList.status
                        });
                    }

                }, 200);
            },
            onSelectChangeC(selectedRowKeys, selectedRows) {
                this.dataList = selectedRows[0];
                this.demoList = selectedRowKeys

                this.locosclete = selectedRowKeys
            },
            delOkA() {
                getonOffAccount({
                    userId: this.okDelkey.userId,
                    status: this.okDelkey.status == "1" ? "0" : "1",
                })
                    .then((res) => {
                        this.getDataListA();
                        this.$refs.delcomA.visible = false
                    })
                    .catch((err) => {
                        console.log(err);
                    });

            },
            onSwitch(text, tags, i) {
                this.$refs.delcomA.visible = true
                this.okDelkey = tags
            },
            handleSubmit(e) {
                e.preventDefault();
                this.form.validateFields((err, values) => {
                    if (!err) {
                        if (this.flag == true) {
                            values["userId"] = 0;
                            values["custId"] = this.forminitialA.custId;
                            if (values["userType"] == '管理员') {
                                values["userType"] = 3
                            } else if (values["userType"] == '普通管理员') {
                                values["userType"] = 4
                            } else {
                                values["userType"]= values.userType
                            }
                            getsaveSysUser(values)
                                .then((res) => {
                                    if (res.data.success == true) {
                                        this.$message.success("添加成功");
                                    }
                                    if (res.data.success == false) {
                                        this.$message.error("添加失败");
                                    }
                                })
                                .catch((err) => {
                                    this.$message.error("操作失败");
                                });
                        } else {
                            let demo = {}
                            demo.nickname = values.nickname
                            demo.password = values.password
                            demo.userCode = values.userCode
                            demo.userId = this.dataList.userId
                            demo.status = values.status
                            demo.empId = values.empId
                            if (values.userType == '管理员') {
                                demo.userType = 3
                            } else if (values.userType == '普通管理员') {
                                demo.userType = 4
                            } else {
                                demo.userType = values.userType
                            }
                            console.log(demo)
                            console.log(values)

                            getsaveSysUser(demo)
                                .then((res) => {
                                    if (res.data.success == true) {
                                        this.getDataListA()
                                        this.$message.success("添加成功");
                                    }
                                    if (res.data.success == false) {
                                        this.$message.error("添加失败");
                                    }
                                })
                                .catch((err) => {
                                    this.$message.error("操作失败");
                                });
                        }

                        this.userVisible = false;
                        this.form.resetFields();
                    }
                });
            },
            tableHandleOk() {
                this.locosclete = []
            },
            tableHandleCancel() {
                this.locosclete = []
                setTimeout(() => {
                    this.form.setFieldsValue({
                        userType: "",
                        userCode: "",
                        nickname: "",
                        empId: "",
                        status: "",
                        userId: ""
                    });

                }, 200);
                console.log("aa");
                this.tableVisible = false;
            },
            getDataListA() {
                getCustSysUserList({
                    params: JSON.parse(JSON.stringify(this.forminitialA)),
                })
                    .then((res) => {
                        this.dataA = res.data.data;
                        console.log(res);
                    })
                    .catch((err) => {
                        console.log(err);
                    });
            },
            showTable(text, tags, i) {
                console.log(tags);
                this.forminitialA.custId = tags.custid;
                this.getDataListA();

                this.tableVisible = true;
            },
            userHandleCancel() {
                this.userVisible = false;
                this.handleUserType = 'add';
                this.form.resetFields()
            },
            addUser() {
                this.flag = true
                this.handleUserType = 'add';
                if (this.radioFlag == false)
                    return this.$message.warning("请选择客户信息");
                this.userVisible = true;
                setTimeout(() => {
                    this.form.setFieldsValue({
                        userType: '管理员',
                        status: 1
                    });
                }, 200);
            },
            onSelectChange(selectedRowKeys, selectedRows) {
                this.radioFlag = true;
                this.forminitialA.custId = selectedRows[0].custid;

                console.log(selectedRows[0]);
            },
            schoolChange(val) {
                this.forminitial.custType = val;
                this.getClientList();
            },
            commChange(val) {
                this.forminitial.custLevel = val;
                this.getClientList();
            },
            onShowSizeChange(page, limit) {
                this.forminitial.page = page;
                this.forminitial.limit = limit;
                this.getClientList();
            },
            Pages(page, pageSize) {
                this.forminitial.limit = pageSize;
                this.forminitial.page = page;
                this.forminitial.start = (page - 1) * pageSize;
                this.getClientList();
            },
            onSearch() {
                this.getClientList();
            },
            getClientList() {
                getCustomerList({params: this.forminitial})
                    .then((res) => {
                        this.total = res.data.total;
                        this.data = res.data.data;
                        console.log(res.data.data)
                        res.data.data.forEach((item) => {
                            if (item.custlevel == 0) {
                                item.custlevel = "云麦";
                            }
                            if (item.custlevel == 1) {
                                item.custlevel = "代理商";
                            }
                            if (item.custlevel == 2) {
                                item.custlevel = "具体使用客户";
                            }
                            if (item.custtype == 1) {
                                item.custtype = "企业单位";
                            }
                            if (item.custtype == 2) {
                                item.custtype = "幼儿园中小学";
                            }
                            if (item.custtype == 3) {
                                item.custtype = "中专高职高专大学";
                            }
                        });
                    })
                    .catch((err) => {
                        console.log(err);
                    });
            },
        },
    };
</script>

<style>
</style>